<?php
/**
 * admin_setting 数据表模型
 * @author  haiwera <zhanhh@pvc123.com>
 */

namespace models;
use herosphp\core\WebApplication;
use herosphp\cache\CacheFactory;

class AdminSettingModel extends C_Model {

	private static $__cacheCtrl ;
	private static $__hasModified = false;
	private static $__configs = array();
    public function __construct() {

        //创建model对象并初始化数据表名称
        parent::__construct('admin_setting');

        //设置表数据表主键，默认为id
        $this->setPrimaryKey('id');
		$this->autoPrimary = false;
        //客户机运行不需要缓存
		if(self::$__cacheCtrl == null && !defined('RUN_CLI'))
		{
			$config = WebApplication::getInstance()->getConfigs();
			$cachetype = $config['cache_type'];

			self::$__cacheCtrl = CacheFactory::create($cachetype);
		}

    }

	public function getConfigs()
	{
		if(empty($this->__configs))
		{
			$this->flush();
		}

		return $this->__configs;
		
			
	}
	public function flush()
	{
		$cache = self::$__cacheCtrl->baseKey('system')->ftype('setting')->factor(appId());
		$result = $cache->get();
		if(!$result || self::$__hasModified)
		{
			$list = $this->getItems(array('app_id' => appId()),null,null,array(1,10000));
			$result = array();
			foreach($list as $v)
			{
				$result[$v['name']] = $v['value'];
			}
			$cache->set(null,$result);
		}
		$this->__configs = $result;
		self::$__hasModified = false;
	}
	public function add($data)
	{
		foreach($data as $k => $v)
		{
			if($v == NULL)
			{
				$data[$k] = '';
			}
		}
		$rs = parent::add($data);
		if($rs)
		{
			self::$__hasModified = true;
			$this->flush();
		}
		return $rs;
	}
	/*
	* @override 
	*/
	public function update($data,$id)
	{
		foreach($data as $k => $v)
		{
			if($v == NULL)
			{
				$data[$k] = '';
			}
		}
		$rs = parent::update($data,$id);
		if($rs)
		{
			self::$__hasModified = true;
			$this->flush();

		}
		return $rs;
	}

	public function updates($data,$condition){
			
		foreach($data as $k => $v)
		{
			if($v == NULL)
			{
				$data[$k] = '';
			}
		}
		$rs = parent::updates($data,$condition);
		if($rs)
		{
			self::$__hasModified = true;
			$this->flush();

		}
		return $rs;
	
	}

	/*
	* @override : 删除权限
	*/

	public function delete($id)
	{
		$rs = parent::delete($id);
		if($rs)
		{
			self::$__hasModified = true;
			$this->flush();
		}
		return $rs;
	}
} 
